#include "SList.h"

SLTNode* SLTBuyNode(SLTDataType x)
{
	SLTNode* newnode = (SLTNode*)malloc(sizeof(SLTNode));
	if (newnode == NULL)
	{
		perror("malloc");
		exit(1);
	}
	newnode->data = x;
	newnode->next = NULL;
	return newnode;
}


//void SLTPrint(SLTNode* phead)
//{
//	SLTNode* pcur = phead;
//	while (pcur)
//	{
//		printf("%d->", pcur->data);
//		pcur = pcur->next;
//	}
//	printf("NULL\n");
//}


void SLTPushFront(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* newnode = SLTBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		newnode->next = *pphead;
		*pphead = newnode;
	}
}

void SLTPushBack(SLTNode** pphead, SLTDataType x)
{
	assert(pphead);
	SLTNode* pcur = *pphead;
	SLTNode* newnode = SLTBuyNode(x);
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		while (pcur->next)
		{
			pcur = pcur->next;
		}
		pcur->next = newnode;
	}
}



void SLTPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* pcur = *pphead;
	SLTNode* prev = *pphead;
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		while (pcur->next)
		{
			prev = pcur;
			pcur = pcur->next;
		}
		free(pcur);
		prev->next = NULL;
	}
}


void SLTPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* del = *pphead;
	if ((*pphead)->next == NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		*pphead = del->next;
		free(del);
		del = NULL;
	}
}


//SLTNode* SLTFind(SLTNode* phead, SLTDataType x)
//{
//	SLTNode* pcur = phead;
//	while (pcur)
//	{
//		if (pcur->data == x)
//			return pcur;
//		pcur = pcur->next;
//	}
//	return NULL;
//}


void SLTInsert(SLTNode** pphead, SLTNode* pos, SLTDataType x)
{
	assert(pphead&&*pphead);
	assert(pos);
	SLTNode* pcur = *pphead;
	SLTNode* prev = *pphead;
	SLTNode* newnode = SLTBuyNode(x);
	if (pos == *pphead)
	{
		*pphead = newnode;
		newnode->next = pos;
	}
	else
	{
		while (pcur!= pos)
		{
			prev = pcur;
			pcur = pcur->next;
		}
		prev->next = newnode;
		newnode->next = pos;
	}
}

void SLTInsertAfter(SLTNode* pos, SLTDataType x)
{
	assert(pos->next);
	assert(pos);
	SLTNode* newnode = SLTBuyNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}


void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && *pphead);
	assert(pos);
	SLTNode* pcur = *pphead;
	SLTNode* prev = *pphead;
	if (pos == *pphead)
	{
		*pphead = pos->next;
		free(pos);
		pos = NULL;
	}
	else
	{
		while (pcur!= pos)
		{
			prev = pcur;
			pcur = pcur->next;
		}
		prev->next = pos->next;
		free(pos);
		pos = NULL;
	}
}

void SLTEraseAfter(SLTNode* pos)
{
	assert(pos&&pos->next);
	SLTNode* del = pos->next;
	pos->next = del->next;
	free(del);
	del = NULL;
}


void SLTDestroy(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* pcur = *pphead;
	SLTNode* prev = *pphead;
	while (pcur)
	{
		prev = pcur;
		pcur = pcur->next;
		free(prev);
	}
	*pphead = NULL;
}